package com.zhimeng.personal.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by sunzhimeng on 10/31/17.
 */

public class FileUtil {
    private static final File parentPath = Environment.getExternalStorageDirectory();
    private static String storagePath = "";
    private static String DST_FOLDER_NAME = "Personal";
    private static String AMAP_COONFIG_FILE = "personal_amap.data";
    private static String SEPARATER = "/";

    private static String initAppRootPath() {
        if (storagePath.equals("")) {
            storagePath = parentPath.getAbsolutePath() + SEPARATER + DST_FOLDER_NAME;
            File f = new File(storagePath);
            if (!f.exists()) {
                f.mkdir();
            }
        }
        return storagePath;
    }

    public static String getAmapThemeConfigFile(Context context) {
        String configFilePath = initAppRootPath() + SEPARATER + AMAP_COONFIG_FILE;
        if (exist(configFilePath)) return configFilePath;
        try {
            InputStream is = context.getAssets().open(AMAP_COONFIG_FILE);
            FileOutputStream fos = new FileOutputStream(new File(configFilePath));
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return configFilePath;
    }

    public static boolean exist(String path){
        return new File(path).exists();
    }

    public static String saveBitmap(String dir, Bitmap b) {
        DST_FOLDER_NAME = dir;
        String path = initAppRootPath();
        long dataTake = System.currentTimeMillis();
        String jpegName = path + File.separator + "picture_" + dataTake + ".jpg";
        try {
            FileOutputStream fout = new FileOutputStream(jpegName);
            BufferedOutputStream bos = new BufferedOutputStream(fout);
            b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            return jpegName;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }
}
